package com.fwtai.service.web;

import com.fwtai.bean.PageFormData;
import com.fwtai.tool.ToolClient;
import com.fwtai.tool.ToolString;
import com.fwtai.web.OrderInfoDao;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 微信支付订单业务层
 * @作者 田应平
 * @版本 v1.0
 * @QQ号码 444141300
 * @Email service@fwtai.com
 * @创建日期 2024-02-28 18:03:36
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class OrderInfoService{

  private final OrderInfoDao orderInfoDao;

  private final ThreadPoolTaskExecutor taskExecutor;

  public OrderInfoService(final OrderInfoDao orderInfoDao,final ThreadPoolTaskExecutor taskExecutor){
    this.orderInfoDao = orderInfoDao;
    this.taskExecutor = taskExecutor;
  }

  public String queryById(final Long kid){
    return CompletableFuture.supplyAsync(()->{
      if(kid == null){
        return ToolClient.jsonValidateField();
      }
      return ToolClient.queryJson(orderInfoDao.queryById(kid));
    },taskExecutor).join();
  }

  public String listData(final PageFormData formData){
    return CompletableFuture.supplyAsync(()->{
      try{
        if(ToolClient.dataTableMysql(formData) == null) return ToolClient.jsonValidateField();
        ToolString.handlerAreaData(formData,null);
        final String buyer_type = "buyer_type";
        if(formData.containsKey(buyer_type)){
          formData.put(buyer_type,formData.getInteger(buyer_type));
        }
        final BigDecimal totalMoney = orderInfoDao.getOrderTotalMoney(formData);
        final Integer salesVolume = orderInfoDao.getOrderSalesVolume(formData);
        final HashMap<String,Object> attach = new HashMap<>(2);
        attach.put("totalMoney",totalMoney);
        attach.put("salesVolume",salesVolume);
        final CompletableFuture<List<HashMap<String,Object>>> listData = CompletableFuture.supplyAsync(() -> orderInfoDao.getListData(formData),taskExecutor);
        final CompletableFuture<Integer> listTotal = CompletableFuture.supplyAsync(() -> orderInfoDao.getListTotal(formData),taskExecutor);
        return ToolClient.dataTableOK(listData.join(),listTotal.join(),attach);
      } catch (final Exception ignored){
        return ToolClient.dataTableException();
      }
    },taskExecutor).join();
  }
}